package org.wisdom.security.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.stereotype.Component;
import org.wisdom.context.WisdomContextHolder;

import java.util.Collections;

/**
 * token认证服务
 * 
 * @author zhangzhiyan
 * @date 2021/08/19 16:01
 **/
@Slf4j
@Component
public class InsideAuthenticationProvider implements AuthenticationProvider {

    @Value("${wisdom.feign.secretKey:S32^&sdfSdx231*23f!3#xWe}")
    private String wisdomFeignSecretKey;

    @Override
    public Authentication authenticate(Authentication authentication) {
        String feignPre = "SK ";
        String authorizationHeader = authentication.getName();
        if(authorizationHeader.startsWith(feignPre)) {
            log.debug("开始SK认证{}", authorizationHeader);
            PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
            String secretKey = authorizationHeader.replace(feignPre, "");
            boolean checkResult = passwordEncoder.matches(this.wisdomFeignSecretKey, secretKey);
            if(checkResult) {
                WisdomContextHolder.getContext().setUserId("system");
                return new UsernamePasswordAuthenticationToken("system", null, Collections.emptyList());
            }
        }
        return null;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return PreAuthenticatedAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
